import * as apis from '@/apis/modules/manage.js';

const manageDetail = {
	namespaced: true,
	state: {
		detail: {},
		list: [],
		pageNum: 1,
		hasData: true
	},
	mutations: {
		save(state, {field, payload}) {
		  if (Object.prototype.toString.call(payload) === '[object Object]') {
			state[field] = { ...state[field], ...payload }
		  } else {
			state[field] = payload
		  }
		}
	},
	actions: {
		getDetail({ commit }, payload) {
			apis.getDetail(payload)
				.then(({error, data}) => {
					if (error) return
					
					commit('save', {field: 'detail', payload: data})
				})
			
		},
		getTradeList({ commit }, payload) {
			apis.getTradeList(payload)
				.then(({error, data}) => {
					if (error) return
					
					if (!data) return
					const {pages, records} = data
					let {list: recordList} = state

					if (pageNum > 1) {
						recordList = recordList.concat(records)
					} else {
						recordList = records || []
					}

					if (pages === pageNum || pages === 0 || !pages) commit('save', {field: 'hasData', payload: false})

					commit('save', {field: 'pageNum', payload: pageNum})
					commit('save', {field: 'list', payload: recordList})
				})
		}
	}
}

export default manageDetail